const CryptoJS = require('./cryAes.js'); //引用AES源码js
//const key = CryptoJS.enc.Utf8.parse("0102030405060708"); //十六位十六进制数作为秘钥
const iv = CryptoJS.enc.Utf8.parse('0102030405060708'); //十六位十六进制数作为秘钥偏移量
//aes 解密方法
function AesDecrypt(word, key) {
  if (word == undefined || word == '')
    return word;

  const keyMd5 = CryptoJS.MD5(key).toString()
  const keyUtf8 = CryptoJS.enc.Utf8.parse(keyMd5);
  const encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  const decrypt = CryptoJS.AES.decrypt(srcs, keyUtf8, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return decrypt.toString(CryptoJS.enc.Utf8).toString();
}
//aes 加密方法
function AesEncrypt(word, key) {
  if (word == undefined || word == '')
    return word;

  const keyMd5 = CryptoJS.MD5(key).toString()
  const keyUtf8 = CryptoJS.enc.Utf8.parse(keyMd5);
  const srcs = CryptoJS.enc.Utf8.parse(word);
  const encrypted = CryptoJS.AES.encrypt(srcs, keyUtf8, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.ciphertext.toString().toUpperCase();
}
//base64 加密方法
function Base64Encode(val) {
  if (val == undefined || val == '')
    return val;

  let str = CryptoJS.enc.Utf8.parse(val);
  let base64 = CryptoJS.enc.Base64.stringify(str);
  return base64;
}
//base64 解密方法
function Base64Decode(val) {
  if (val == undefined || val == '')
    return val;

  let words = CryptoJS.enc.Base64.parse(val);
  return words.toString(CryptoJS.enc.Utf8);
}
//md5 加密方法
function MD5Encrypt(word) {
  return CryptoJS.MD5(word).toString();
}

//暴露接口
module.exports = {
  AesEncrypt,
  AesDecrypt,
  Base64Encode,
  Base64Decode,
  MD5Encrypt,
}